<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\User as UserModel;
use think\Response;
use app\exception\UserTokenExpiredException;

class Check
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $path = $request->pathinfo();

        $token = $request->header('token','');

        // 登录请求 或 验证登录状态请求,放行
        if ($path == "user/login" || $path == "user/isLogin" || $path == "product/firstGetProductList" || $path == "product/getProductInfo" || $path == "product/getProductList") {
            return $next($request);
        }

        // 不是登录请求 或 验证登录状态请求，且没有token的话，拦截请求
        if (empty($token)){
            // 拦截请求，返回 JSON 错误响应
            return Response::create([
                'code' => 401,
                'msg'  => '未登录'
            ], "json");
        }else{
            // 不是登录请求 或 验证登录状态的请求，但是携带了token,则验证token是否有效

            try {
                $result = UserModel::isLogin($token);

                // token有效，存储用户信息
                $request->user = $result['user'];

                // 验证通过，放行
                return $next($request);

            }catch (UserTokenExpiredException $e){

                // token过期
                return Response::create([
                    'code' => $e->getCode(),
                    'msg'  => $e->getMessage()
                ], "json");

            }catch (\Exception $e){

                // 系统异常
                return Response::create([
                    'code' => 500,
                    'msg'  => '系统错误'
                ], "json",500);

            }
        }
    }
}
